/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.worsik.vypocty.topeni.tepelneztraty.view.mistnosti;

import cz.worsik.vypocty.topeni.tepelneztraty.model.Mistnost;
import cz.worsik.vypocty.topeni.tepelneztraty.model.table.OtvoryTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;

/**
 *
 * @author 231260
 */
public final class OtvoryTable extends JTable {
	
	public OtvoryTable(OtvoryTableModel model)
	{
		super(model);
		setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
		aktualizujTabulku();
	}
	
	public void addPopupListener()
	{
		addMouseListener(new PopupListener());
	}
	
	public void aktualizujTabulku()
	{
		JTableHeader header = getTableHeader();
		for (int i = 0; i < getModel().getColumnCount(); i++)
		{
			TableColumn col = header.getColumnModel().getColumn(i);
			
			col.setResizable(false);
			col.setPreferredWidth(getModel().getColumnWidth(i));
		}
		// TODO misto listu sten vytvorit tridu, ktera implementuje TableModel
	}
	
	@Override
	public OtvoryTableModel getModel()
	{
		TableModel model = super.getModel();
		if (model instanceof OtvoryTableModel)
			return (OtvoryTableModel) model;
		else
			return null;
	}
	
	public void removeOtvor()
	{
		int row = getSelectedRow();
		
		if (row >= 0)
			getModel().removeOtvor(row);
	}
	
	public class PopupListener extends MouseAdapter
	{
		@Override
        public void mouseReleased(MouseEvent e) 
		{
            int r = rowAtPoint(e.getPoint());
            if (r >= 0 && r < getRowCount()) {
                setRowSelectionInterval(r, r);
            } else {
                clearSelection();
            }

            int rowindex = getSelectedRow();
            if (rowindex < 0)
                return;
            if (e.isPopupTrigger() && e.getComponent() instanceof JTable ) {
                JPopupMenu popup = new JPopupMenu();
				
				JMenuItem smaz = new JMenuItem("Odstranit otvor");
				smaz.addActionListener(new ActionListener() {

					@Override
					public void actionPerformed(ActionEvent ae) {
						removeOtvor();
					}
				});
				
				popup.add(smaz);
				
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        }
	}
}
